#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
增强验证系统 v2.0
专为重装系统后的持久化测试验证设计
提供详细的状态检查、日志分析和智能诊断功能
"""

import os
import sys
import json
import time
import subprocess
import threading
import signal
import logging
import hashlib
import psutil
from datetime import datetime, timedelta
from pathlib import Path
from typing import Dict, List, Tuple, Optional, Any

class EnhancedVerificationSystem:
    """增强验证系统"""
    
    def __init__(self):
        self.version = "2.0.0"
        self.session_id = datetime.now().strftime("%Y%m%d_%H%M%S")
        self.start_time = time.time()
        
        # 配置路径
        self.base_dir = Path("/tmp/persistence_verification")
        self.log_dir = self.base_dir / "logs"
        self.report_dir = self.base_dir / "reports"
        self.backup_dir = self.base_dir / "backups"
        
        # 创建目录
        for dir_path in [self.base_dir, self.log_dir, self.report_dir, self.backup_dir]:
            dir_path.mkdir(parents=True, exist_ok=True)
        
        # 配置日志
        self.setup_logging()
        
        # 验证配置
        self.verification_config = {
            'ssh_key': {
                'files': ['/root/.ssh/authorized_keys'],
                'processes': [],
                'services': ['ssh', 'sshd'],
                'ports': [22],
                'logs': ['/var/log/auth.log', '/var/log/secure']
            },
            'systemd_service': {
                'files': ['/etc/systemd/system/persistence-test.service'],
                'processes': ['persistence-test'],
                'services': ['persistence-test'],
                'ports': [],
                'logs': ['/var/log/syslog', '/var/log/messages']
            },
            'crontab': {
                'files': ['/etc/crontab', '/var/spool/cron/root'],
                'processes': ['cron', 'crond'],
                'services': ['cron', 'crond'],
                'ports': [],
                'logs': ['/var/log/cron', '/var/log/cron.log']
            },
            'env_variable': {
                'files': ['/root/.bashrc', '/etc/environment'],
                'processes': [],
                'services': [],
                'ports': [],
                'logs': []
            },
            'file_trigger': {
                'files': ['/tmp/test_trigger.txt'],
                'processes': ['inotifywait'],
                'services': [],
                'ports': [],
                'logs': []
            },
            'alias': {
                'files': ['/root/.bashrc'],
                'processes': [],
                'services': [],
                'ports': [],
                'logs': []
            }
        }
        
        # 验证结果
        self.verification_results = {}
        self.detailed_results = {}
        self.performance_metrics = {}
        
        self.logger.info(f"增强验证系统 v{self.version} 初始化完成")
        self.logger.info(f"会话ID: {self.session_id}")
    
    def setup_logging(self):
        """设置日志系统"""
        log_file = self.log_dir / f"verification_{self.session_id}.log"
        
        # 配置日志格式
        log_format = '%(asctime)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s'
        
        # 配置日志记录器
        logging.basicConfig(
            level=logging.INFO,
            format=log_format,
            handlers=[
                logging.FileHandler(log_file, encoding='utf-8'),
                logging.StreamHandler(sys.stdout)
            ]
        )
        
        self.logger = logging.getLogger(__name__)
        self.logger.info("日志系统初始化完成")
    
    def run_command(self, command: str, timeout: int = 30) -> Tuple[bool, str, str]:
        """执行系统命令"""
        try:
            self.logger.debug(f"执行命令: {command}")
            
            result = subprocess.run(
                command,
                shell=True,
                capture_output=True,
                text=True,
                timeout=timeout
            )
            
            success = result.returncode == 0
            stdout = result.stdout.strip()
            stderr = result.stderr.strip()
            
            if not success:
                self.logger.warning(f"命令执行失败: {command}")
                self.logger.warning(f"错误输出: {stderr}")
            
            return success, stdout, stderr
            
        except subprocess.TimeoutExpired:
            self.logger.error(f"命令执行超时: {command}")
            return False, "", "命令执行超时"
        except Exception as e:
            self.logger.error(f"命令执行异常: {command}, 错误: {str(e)}")
            return False, "", str(e)
    
    def verify_file_existence(self, file_path: str) -> Dict[str, Any]:
        """验证文件存在性和属性"""
        result = {
            'exists': False,
            'size': 0,
            'permissions': '',
            'owner': '',
            'modified_time': '',
            'content_hash': '',
            'readable': False,
            'writable': False
        }
        
        try:
            path = Path(file_path)
            
            if path.exists():
                result['exists'] = True
                stat_info = path.stat()
                
                result['size'] = stat_info.st_size
                result['permissions'] = oct(stat_info.st_mode)[-3:]
                result['modified_time'] = datetime.fromtimestamp(stat_info.st_mtime).isoformat()
                
                # 获取所有者信息
                success, stdout, _ = self.run_command(f"ls -l {file_path}")
                if success and stdout:
                    parts = stdout.split()
                    if len(parts) >= 3:
                        result['owner'] = f"{parts[2]}:{parts[3]}"
                
                # 检查读写权限
                result['readable'] = os.access(file_path, os.R_OK)
                result['writable'] = os.access(file_path, os.W_OK)
                
                # 计算文件哈希（小文件）
                if result['size'] < 1024 * 1024:  # 1MB以下
                    try:
                        with open(file_path, 'rb') as f:
                            content = f.read()
                            result['content_hash'] = hashlib.md5(content).hexdigest()
                    except:
                        pass
                
                self.logger.debug(f"文件验证成功: {file_path}")
            else:
                self.logger.debug(f"文件不存在: {file_path}")
                
        except Exception as e:
            self.logger.error(f"文件验证失败: {file_path}, 错误: {str(e)}")
        
        return result
    
    def verify_process_running(self, process_name: str) -> Dict[str, Any]:
        """验证进程运行状态"""
        result = {
            'running': False,
            'count': 0,
            'pids': [],
            'cpu_usage': 0.0,
            'memory_usage': 0.0,
            'start_time': '',
            'command_line': []
        }
        
        try:
            matching_processes = []
            
            for proc in psutil.process_iter(['pid', 'name', 'cmdline', 'create_time', 'cpu_percent', 'memory_percent']):
                try:
                    proc_info = proc.info
                    if process_name.lower() in proc_info['name'].lower() or \
                       any(process_name.lower() in arg.lower() for arg in proc_info['cmdline']):
                        matching_processes.append(proc_info)
                except (psutil.NoSuchProcess, psutil.AccessDenied):
                    continue
            
            if matching_processes:
                result['running'] = True
                result['count'] = len(matching_processes)
                result['pids'] = [proc['pid'] for proc in matching_processes]
                result['cpu_usage'] = sum(proc['cpu_percent'] or 0 for proc in matching_processes)
                result['memory_usage'] = sum(proc['memory_percent'] or 0 for proc in matching_processes)
                
                # 获取最早启动的进程信息
                earliest_proc = min(matching_processes, key=lambda x: x['create_time'])
                result['start_time'] = datetime.fromtimestamp(earliest_proc['create_time']).isoformat()
                result['command_line'] = earliest_proc['cmdline']
                
                self.logger.debug(f"进程验证成功: {process_name}, 找到 {result['count']} 个进程")
            else:
                self.logger.debug(f"进程未运行: {process_name}")
                
        except Exception as e:
            self.logger.error(f"进程验证失败: {process_name}, 错误: {str(e)}")
        
        return result
    
    def verify_service_status(self, service_name: str) -> Dict[str, Any]:
        """验证系统服务状态"""
        result = {
            'exists': False,
            'active': False,
            'enabled': False,
            'status': '',
            'uptime': '',
            'restart_count': 0,
            'last_restart': ''
        }
        
        try:
            # 检查服务是否存在
            success, stdout, _ = self.run_command(f"systemctl list-unit-files {service_name}.service")
            if success and service_name in stdout:
                result['exists'] = True
                
                # 检查服务状态
                success, stdout, _ = self.run_command(f"systemctl is-active {service_name}")
                if success:
                    result['active'] = stdout.strip() == 'active'
                    result['status'] = stdout.strip()
                
                # 检查服务是否启用
                success, stdout, _ = self.run_command(f"systemctl is-enabled {service_name}")
                if success:
                    result['enabled'] = stdout.strip() == 'enabled'
                
                # 获取详细状态信息
                success, stdout, _ = self.run_command(f"systemctl status {service_name}")
                if success:
                    lines = stdout.split('\n')
                    for line in lines:
                        if 'Active:' in line:
                            if 'since' in line:
                                parts = line.split('since')
                                if len(parts) > 1:
                                    result['uptime'] = parts[1].strip()
                
                self.logger.debug(f"服务验证成功: {service_name}")
            else:
                self.logger.debug(f"服务不存在: {service_name}")
                
        except Exception as e:
            self.logger.error(f"服务验证失败: {service_name}, 错误: {str(e)}")
        
        return result
    
    def verify_port_listening(self, port: int) -> Dict[str, Any]:
        """验证端口监听状态"""
        result = {
            'listening': False,
            'protocol': '',
            'process_name': '',
            'pid': 0,
            'address': ''
        }
        
        try:
            # 使用netstat检查端口
            success, stdout, _ = self.run_command(f"netstat -tlnp | grep :{port}")
            if success and stdout:
                lines = stdout.strip().split('\n')
                for line in lines:
                    if f':{port}' in line:
                        parts = line.split()
                        if len(parts) >= 4:
                            result['listening'] = True
                            result['protocol'] = parts[0]
                            result['address'] = parts[3]
                            
                            # 提取进程信息
                            if len(parts) >= 7 and '/' in parts[6]:
                                pid_name = parts[6].split('/')
                                result['pid'] = int(pid_name[0])
                                result['process_name'] = pid_name[1]
                        break
                
                if result['listening']:
                    self.logger.debug(f"端口验证成功: {port}")
                else:
                    self.logger.debug(f"端口未监听: {port}")
            else:
                self.logger.debug(f"端口未监听: {port}")
                
        except Exception as e:
            self.logger.error(f"端口验证失败: {port}, 错误: {str(e)}")
        
        return result
    
    def analyze_log_files(self, log_files: List[str], keywords: List[str] = None) -> Dict[str, Any]:
        """分析日志文件"""
        result = {
            'files_analyzed': 0,
            'total_lines': 0,
            'keyword_matches': 0,
            'recent_entries': [],
            'error_entries': [],
            'warning_entries': []
        }
        
        if keywords is None:
            keywords = ['persistence', 'test', 'backdoor', 'ssh', 'cron', 'systemd']
        
        try:
            for log_file in log_files:
                if not os.path.exists(log_file):
                    continue
                
                result['files_analyzed'] += 1
                
                # 读取最近的日志条目
                success, stdout, _ = self.run_command(f"tail -100 {log_file}")
                if success and stdout:
                    lines = stdout.split('\n')
                    result['total_lines'] += len(lines)
                    
                    for line in lines:
                        line_lower = line.lower()
                        
                        # 检查关键词匹配
                        for keyword in keywords:
                            if keyword.lower() in line_lower:
                                result['keyword_matches'] += 1
                                result['recent_entries'].append({
                                    'file': log_file,
                                    'line': line.strip(),
                                    'keyword': keyword
                                })
                                break
                        
                        # 检查错误和警告
                        if any(level in line_lower for level in ['error', 'err', 'failed', 'fail']):
                            result['error_entries'].append({
                                'file': log_file,
                                'line': line.strip()
                            })
                        elif any(level in line_lower for level in ['warning', 'warn']):
                            result['warning_entries'].append({
                                'file': log_file,
                                'line': line.strip()
                            })
            
            self.logger.debug(f"日志分析完成: 分析了 {result['files_analyzed']} 个文件")
            
        except Exception as e:
            self.logger.error(f"日志分析失败: 错误: {str(e)}")
        
        return result
    
    def verify_mechanism(self, mechanism: str) -> Dict[str, Any]:
        """验证单个持久化机制"""
        self.logger.info(f"开始验证机制: {mechanism}")
        
        config = self.verification_config.get(mechanism, {})
        result = {
            'mechanism': mechanism,
            'overall_status': False,
            'files': {},
            'processes': {},
            'services': {},
            'ports': {},
            'logs': {},
            'score': 0,
            'max_score': 0,
            'issues': [],
            'recommendations': []
        }
        
        try:
            # 验证文件
            for file_path in config.get('files', []):
                file_result = self.verify_file_existence(file_path)
                result['files'][file_path] = file_result
                
                if file_result['exists']:
                    result['score'] += 1
                else:
                    result['issues'].append(f"文件不存在: {file_path}")
                result['max_score'] += 1
            
            # 验证进程
            for process_name in config.get('processes', []):
                process_result = self.verify_process_running(process_name)
                result['processes'][process_name] = process_result
                
                if process_result['running']:
                    result['score'] += 1
                else:
                    result['issues'].append(f"进程未运行: {process_name}")
                result['max_score'] += 1
            
            # 验证服务
            for service_name in config.get('services', []):
                service_result = self.verify_service_status(service_name)
                result['services'][service_name] = service_result
                
                if service_result['active']:
                    result['score'] += 1
                else:
                    result['issues'].append(f"服务未激活: {service_name}")
                result['max_score'] += 1
            
            # 验证端口
            for port in config.get('ports', []):
                port_result = self.verify_port_listening(port)
                result['ports'][port] = port_result
                
                if port_result['listening']:
                    result['score'] += 1
                else:
                    result['issues'].append(f"端口未监听: {port}")
                result['max_score'] += 1
            
            # 分析日志
            log_files = config.get('logs', [])
            if log_files:
                log_result = self.analyze_log_files(log_files, [mechanism, 'test'])
                result['logs'] = log_result
            
            # 计算总体状态
            if result['max_score'] > 0:
                success_rate = result['score'] / result['max_score']
                result['overall_status'] = success_rate >= 0.5  # 50%以上认为成功
                
                if success_rate < 0.3:
                    result['recommendations'].append("机制可能完全失效，建议重新部署")
                elif success_rate < 0.7:
                    result['recommendations'].append("机制部分工作，建议检查配置")
                else:
                    result['recommendations'].append("机制工作正常")
            
            self.logger.info(f"机制验证完成: {mechanism}, 状态: {result['overall_status']}")
            
        except Exception as e:
            self.logger.error(f"机制验证失败: {mechanism}, 错误: {str(e)}")
            result['issues'].append(f"验证过程异常: {str(e)}")
        
        return result
    
    def verify_all_mechanisms(self) -> Dict[str, Any]:
        """验证所有持久化机制"""
        self.logger.info("开始验证所有持久化机制")
        
        start_time = time.time()
        results = {}
        
        for mechanism in self.verification_config.keys():
            mechanism_result = self.verify_mechanism(mechanism)
            results[mechanism] = mechanism_result
            self.verification_results[mechanism] = mechanism_result['overall_status']
            self.detailed_results[mechanism] = mechanism_result
        
        end_time = time.time()
        
        # 计算性能指标
        self.performance_metrics = {
            'total_time': end_time - start_time,
            'mechanisms_tested': len(results),
            'successful_mechanisms': sum(1 for r in results.values() if r['overall_status']),
            'failed_mechanisms': sum(1 for r in results.values() if not r['overall_status']),
            'success_rate': sum(1 for r in results.values() if r['overall_status']) / len(results) if results else 0
        }
        
        self.logger.info(f"所有机制验证完成，成功率: {self.performance_metrics['success_rate']:.1%}")
        
        return results
    
    def generate_detailed_report(self) -> str:
        """生成详细验证报告"""
        self.logger.info("生成详细验证报告")
        
        report_file = self.report_dir / f"verification_report_{self.session_id}.md"
        
        try:
            with open(report_file, 'w', encoding='utf-8') as f:
                f.write(f"# 增强验证系统报告 v{self.version}\n\n")
                f.write(f"**会话ID**: {self.session_id}\n")
                f.write(f"**生成时间**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
                f.write(f"**验证耗时**: {self.performance_metrics.get('total_time', 0):.2f} 秒\n\n")
                
                # 总体摘要
                f.write("## 📊 验证摘要\n\n")
                f.write(f"- **测试机制数量**: {self.performance_metrics.get('mechanisms_tested', 0)}\n")
                f.write(f"- **成功机制数量**: {self.performance_metrics.get('successful_mechanisms', 0)}\n")
                f.write(f"- **失败机制数量**: {self.performance_metrics.get('failed_mechanisms', 0)}\n")
                f.write(f"- **总体成功率**: {self.performance_metrics.get('success_rate', 0):.1%}\n\n")
                
                # 详细结果
                f.write("## 🔍 详细验证结果\n\n")
                
                for mechanism, result in self.detailed_results.items():
                    status_icon = "✅" if result['overall_status'] else "❌"
                    f.write(f"### {status_icon} {mechanism.upper()}\n\n")
                    
                    f.write(f"**状态**: {'成功' if result['overall_status'] else '失败'}\n")
                    f.write(f"**得分**: {result['score']}/{result['max_score']}\n\n")
                    
                    # 文件验证
                    if result['files']:
                        f.write("#### 📁 文件验证\n\n")
                        for file_path, file_info in result['files'].items():
                            file_status = "✅" if file_info['exists'] else "❌"
                            f.write(f"- {file_status} `{file_path}`\n")
                            if file_info['exists']:
                                f.write(f"  - 大小: {file_info['size']} 字节\n")
                                f.write(f"  - 权限: {file_info['permissions']}\n")
                                f.write(f"  - 所有者: {file_info['owner']}\n")
                        f.write("\n")
                    
                    # 进程验证
                    if result['processes']:
                        f.write("#### 🔄 进程验证\n\n")
                        for process_name, process_info in result['processes'].items():
                            process_status = "✅" if process_info['running'] else "❌"
                            f.write(f"- {process_status} `{process_name}`\n")
                            if process_info['running']:
                                f.write(f"  - 进程数量: {process_info['count']}\n")
                                f.write(f"  - PID: {', '.join(map(str, process_info['pids']))}\n")
                                f.write(f"  - CPU使用率: {process_info['cpu_usage']:.1f}%\n")
                                f.write(f"  - 内存使用率: {process_info['memory_usage']:.1f}%\n")
                        f.write("\n")
                    
                    # 服务验证
                    if result['services']:
                        f.write("#### ⚙️ 服务验证\n\n")
                        for service_name, service_info in result['services'].items():
                            service_status = "✅" if service_info['active'] else "❌"
                            f.write(f"- {service_status} `{service_name}`\n")
                            if service_info['exists']:
                                f.write(f"  - 状态: {service_info['status']}\n")
                                f.write(f"  - 启用: {'是' if service_info['enabled'] else '否'}\n")
                                if service_info['uptime']:
                                    f.write(f"  - 运行时间: {service_info['uptime']}\n")
                        f.write("\n")
                    
                    # 端口验证
                    if result['ports']:
                        f.write("#### 🌐 端口验证\n\n")
                        for port, port_info in result['ports'].items():
                            port_status = "✅" if port_info['listening'] else "❌"
                            f.write(f"- {port_status} 端口 `{port}`\n")
                            if port_info['listening']:
                                f.write(f"  - 协议: {port_info['protocol']}\n")
                                f.write(f"  - 进程: {port_info['process_name']} (PID: {port_info['pid']})\n")
                                f.write(f"  - 地址: {port_info['address']}\n")
                        f.write("\n")
                    
                    # 问题和建议
                    if result['issues']:
                        f.write("#### ⚠️ 发现的问题\n\n")
                        for issue in result['issues']:
                            f.write(f"- {issue}\n")
                        f.write("\n")
                    
                    if result['recommendations']:
                        f.write("#### 💡 建议\n\n")
                        for recommendation in result['recommendations']:
                            f.write(f"- {recommendation}\n")
                        f.write("\n")
                
                # 系统信息
                f.write("## 🖥️ 系统信息\n\n")
                f.write(f"- **操作系统**: {self.get_system_info()}\n")
                f.write(f"- **Python版本**: {sys.version.split()[0]}\n")
                f.write(f"- **验证工具版本**: {self.version}\n\n")
                
                # 日志文件位置
                f.write("## 📋 相关文件\n\n")
                f.write(f"- **详细日志**: `{self.log_dir / f'verification_{self.session_id}.log'}`\n")
                f.write(f"- **JSON报告**: `{self.report_dir / f'verification_report_{self.session_id}.json'}`\n")
                f.write(f"- **备份目录**: `{self.backup_dir}`\n\n")
                
                f.write("---\n")
                f.write(f"*报告由增强验证系统 v{self.version} 自动生成*\n")
            
            self.logger.info(f"详细报告已生成: {report_file}")
            return str(report_file)
            
        except Exception as e:
            self.logger.error(f"生成详细报告失败: {str(e)}")
            return ""
    
    def generate_json_report(self) -> str:
        """生成JSON格式报告"""
        report_file = self.report_dir / f"verification_report_{self.session_id}.json"
        
        try:
            report_data = {
                'metadata': {
                    'version': self.version,
                    'session_id': self.session_id,
                    'timestamp': datetime.now().isoformat(),
                    'system_info': self.get_system_info()
                },
                'performance_metrics': self.performance_metrics,
                'verification_results': self.verification_results,
                'detailed_results': self.detailed_results
            }
            
            with open(report_file, 'w', encoding='utf-8') as f:
                json.dump(report_data, f, ensure_ascii=False, indent=2)
            
            self.logger.info(f"JSON报告已生成: {report_file}")
            return str(report_file)
            
        except Exception as e:
            self.logger.error(f"生成JSON报告失败: {str(e)}")
            return ""
    
    def get_system_info(self) -> str:
        """获取系统信息"""
        try:
            success, stdout, _ = self.run_command("uname -a")
            if success:
                return stdout
            else:
                return "未知系统"
        except:
            return "未知系统"
    
    def print_summary(self):
        """打印验证摘要"""
        print("\n" + "="*70)
        print(f"🔍 增强验证系统 v{self.version} - 验证摘要")
        print("="*70)
        
        print(f"📊 总体统计:")
        print(f"  测试机制: {self.performance_metrics.get('mechanisms_tested', 0)}")
        print(f"  成功机制: {self.performance_metrics.get('successful_mechanisms', 0)}")
        print(f"  失败机制: {self.performance_metrics.get('failed_mechanisms', 0)}")
        print(f"  成功率: {self.performance_metrics.get('success_rate', 0):.1%}")
        print(f"  验证耗时: {self.performance_metrics.get('total_time', 0):.2f} 秒")
        
        print(f"\n📋 详细结果:")
        for mechanism, status in self.verification_results.items():
            status_icon = "✅" if status else "❌"
            result = self.detailed_results.get(mechanism, {})
            score = result.get('score', 0)
            max_score = result.get('max_score', 0)
            print(f"  {status_icon} {mechanism}: {score}/{max_score}")
        
        print(f"\n📁 报告文件:")
        print(f"  详细报告: {self.report_dir / f'verification_report_{self.session_id}.md'}")
        print(f"  JSON报告: {self.report_dir / f'verification_report_{self.session_id}.json'}")
        print(f"  详细日志: {self.log_dir / f'verification_{self.session_id}.log'}")
        
        print("="*70)

def main():
    """主函数"""
    import argparse
    
    parser = argparse.ArgumentParser(description="增强验证系统 v2.0")
    parser.add_argument('--verify', action='store_true', help='执行完整验证')
    parser.add_argument('--mechanism', type=str, help='验证特定机制')
    parser.add_argument('--report-only', action='store_true', help='仅生成报告')
    parser.add_argument('--json', action='store_true', help='生成JSON报告')
    parser.add_argument('--quiet', action='store_true', help='静默模式')
    
    args = parser.parse_args()
    
    # 创建验证系统实例
    verifier = EnhancedVerificationSystem()
    
    try:
        if args.mechanism:
            # 验证特定机制
            result = verifier.verify_mechanism(args.mechanism)
            verifier.detailed_results[args.mechanism] = result
            verifier.verification_results[args.mechanism] = result['overall_status']
            
            if not args.quiet:
                print(f"\n机制 '{args.mechanism}' 验证结果: {'成功' if result['overall_status'] else '失败'}")
                print(f"得分: {result['score']}/{result['max_score']}")
        
        elif args.verify:
            # 执行完整验证
            verifier.verify_all_mechanisms()
        
        # 生成报告
        if not args.report_only:
            if not args.quiet:
                verifier.print_summary()
        
        # 生成详细报告
        verifier.generate_detailed_report()
        
        if args.json:
            verifier.generate_json_report()
        
        # 返回适当的退出码
        success_rate = verifier.performance_metrics.get('success_rate', 0)
        if success_rate >= 0.8:
            sys.exit(0)  # 成功
        elif success_rate >= 0.5:
            sys.exit(1)  # 部分成功
        else:
            sys.exit(2)  # 失败
            
    except KeyboardInterrupt:
        verifier.logger.warning("验证被用户中断")
        sys.exit(130)
    except Exception as e:
        verifier.logger.error(f"验证过程发生异常: {str(e)}")
        sys.exit(1)

if __name__ == "__main__":
    main()